package com.scut.chenlujie.library.clink.core.schedule;

import com.scut.chenlujie.library.clink.core.Connector;
import com.scut.chenlujie.library.clink.core.ScheduleJob;

import java.util.concurrent.TimeUnit;

public class IdleTimeoutScheduleJob extends ScheduleJob {
    public IdleTimeoutScheduleJob(long idleTime , TimeUnit unit , Connector connector){
        super(idleTime,unit,connector);
    }

    @Override
    public void run() {
        long lastActiveTime = connector.getLastActiveTime();
        long idleTimeoutMilliseconds = this.idleTimeoutMillisecond;

        //下一次调度任务的延迟时间 空闲时间：50 当前时间100 最后活跃时间80
        long nextDelay = idleTimeoutMilliseconds - (System.currentTimeMillis() - lastActiveTime);
        if(nextDelay <= 0){ //已经超时
            schedule(idleTimeoutMillisecond);
            try {
                connector.fireIdleTimeoutEvent();
            }catch (Throwable throwable){
                connector.fireExceptionCaught(throwable);
            }

        }else{
            schedule(nextDelay);
        }
    }
}
